﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace ST.Buz.WinService
{
	public class Program
	{
		public static void Main(string[] args)
		{
			// NLog: setup the logger first to catch all errors
#if DEBUG
			var logger = NLogBuilder.ConfigureNLog("nlog.Debug.config").GetCurrentClassLogger();
#else
			var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
#endif
			try
			{
				logger.Debug("应用开始启动...");
				var runAsService = !(Debugger.IsAttached || args.Contains("--console"));
				if (runAsService)
				{
					var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
					var pathToContentRoot = Path.GetDirectoryName(pathToExe);
					Directory.SetCurrentDirectory(pathToContentRoot);
					//logger.Debug("当前路径：" + pathToContentRoot);
				}

				var builder = CreateWebHostBuilder(
					args.Where(arg => arg != "--console").ToArray());

				var host = builder.Build();

				if (runAsService)
				{
					// To run the app without the CustomWebHostService change the next line to host.RunAsService();
					//host.RunAsCustomService();
					host.RunAsService();
				}
				else
				{
					host.Run();
				}
			}
			catch (Exception ex)
			{
				logger.Error(ex, "应用异常中止");
				throw;
			}
			finally
			{
				NLog.LogManager.Shutdown();
			}
		}

		public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
			WebHost.CreateDefaultBuilder(args)
				.ConfigureLogging((ctx, logging) =>
				{
					logging.AddEventLog();
					logging.AddNLog();
				})
				.UseStartup<Startup>();
	}
}
